package org.xin.framework.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.keyvalue.core.IdentifierGenerator;
import org.springframework.stereotype.Component;

/**
 * @author ：xin
 * @date ：Created in 2021/8/8 11:17
 * @description：MP配置
 * @modified By：
 * @version: 2.0
 */
@Configuration
public class MyBatisPlusConfig {

    /**
     * 自动填充
     * @return
     */
    @Bean
    public GlobalConfig globalConfig() {
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setMetaObjectHandler(
                new MetaHandler()
        );
        return globalConfig;
    }

    /**
     * 分页插件
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }


}

@Slf4j
@Component
class MetaHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        //根据属性名称设置值
        this.setFieldValByName("isDelete", false, metaObject);
        //根据属性名称设置值
        this.setFieldValByName("createTime", DateUtil.now(), metaObject);
        try {
//            this.setFieldValByName("createBy", "", metaObject);
        }catch (Exception e) {
            log.error("当前未登录录用户");
        }
    }

    /**
     * 更新数据执行
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", DateUtil.now(), metaObject);
        try {
//            this.setFieldValByName("updateBy", "", metaObject);
        }catch (Exception e) {
            log.error("当前未登录录用户");
        }
    }
}

